import sys
import os
# 添加项目根目录到Python路径
sys.path.append(os.path.join(os.path.dirname(__file__), '..', '..'))

from flask import Blueprint, jsonify, request
from flask_jwt_extended import jwt_required, get_jwt_identity
from backend.db.db_helpers import query_db

analytics_bp = Blueprint('analytics', __name__)

@analytics_bp.route('/stats', methods=['GET'])
@jwt_required()
def get_statistics():
    """获取统计数据"""
    try:
        user_id = get_jwt_identity()
        
        # 获取用户角色
        user = query_db('SELECT * FROM users WHERE id = ?', [user_id], one=True)
        if not user:
            return jsonify({'error': '用户不存在'}), 404
            
        # 如果是学生，只返回自己的统计数据
        if user['role'] == 'student':
            stats = {
                'total_questions': query_db('SELECT COUNT(*) as count FROM questions WHERE user_id = ?', [user_id], one=True)['count'],
                'subject_distribution': []
            }
            
            subjects = query_db('''
                SELECT s.name, COUNT(q.id) as count
                FROM subjects s
                LEFT JOIN questions q ON s.code = q.subject_code AND q.user_id = ?
                GROUP BY s.code, s.name
            ''', [user_id])
            
            stats['subject_distribution'] = [{'subject': row['name'], 'count': row['count']} for row in subjects]
            
            return jsonify(stats), 200
            
        # 如果是教师，返回所有学生的统计数据
        elif user['role'] == 'teacher':
            stats = {
                'total_students': query_db('SELECT COUNT(*) as count FROM users WHERE role = ?', ['student'], one=True)['count'],
                'total_questions': query_db('SELECT COUNT(*) as count FROM questions', one=True)['count'],
                'subject_stats': []
            }
            
            subject_stats = query_db('''
                SELECT s.name, COUNT(q.id) as question_count
                FROM subjects s
                LEFT JOIN questions q ON s.code = q.subject_code
                GROUP BY s.code, s.name
                ORDER BY question_count DESC
            ''')
            
            stats['subject_stats'] = [{'subject': row['name'], 'questions': row['question_count']} for row in subject_stats]
            
            return jsonify(stats), 200
            
        else:
            return jsonify({'error': '无效的用户角色'}), 400
            
    except Exception as e:
        return jsonify({'error': f'获取统计数据失败: {str(e)}'}), 500